package app

import activity.MainActivity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import ext.log
import manager.AppManager
import manager.TaskManager

private lateinit var INSTANCE: Application

class App : Application(), Thread.UncaughtExceptionHandler, Runnable {
    companion object {
        private const val PROCESS = "com.hontech.kdxclient"
    }

    override fun uncaughtException(t: Thread?, e: Throwable?) {
        e?.printStackTrace()
        AppManager.resetApp()
    }

    override fun onCreate() {
        super.onCreate()
        val name = processName()
        log(name, "进程名称")
        if (name != PROCESS) {
            return
        }
        INSTANCE = this
        MainActivity.isShow = false
        TaskManager.AsyncHandler.postDelayed(this, 10 * 1000)
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    private fun processName(): String {
        val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningApps = am.getRunningAppProcesses()
        for (proInfo in runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                return proInfo.processName
            }
        }
        return ""
    }

    override fun run() {
        AppManager.checkApplication()
        TaskManager.AsyncHandler.postDelayed(this, 3 * 60 * 1000)
    }
}

object AppContext : ContextWrapper(INSTANCE)
